using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MyHomeworkWebAPi.Services
{
    /// <summary>
    /// 订单服务实现类
    /// </summary>
    public class OrderServices : IOrderServices
    {
        private readonly SecondHandTradingPlatformContext _context;
        private readonly JsonSerializerOptions _jsonOptions;

        /// <summary>
        /// 构造函数，注入数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public OrderServices(SecondHandTradingPlatformContext context)
        {
            _context = context;
            _jsonOptions = new JsonSerializerOptions
            {
                ReferenceHandler = ReferenceHandler.IgnoreCycles,
                WriteIndented = true,
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
        }

        /// <summary>
        /// 获取所有订单
        /// </summary>
        public async Task<List<Order>> GetAllAsync()
        {
            return await _context.Orders
                .Include(o => o.User)
                .Include(o => o.Product)
                .OrderByDescending(o => o.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取订单
        /// </summary>
        public async Task<Order> GetByIdAsync(Guid orderId)
        {
            return await _context.Orders
                .Include(o => o.User)
                .Include(o => o.Product)
                .FirstOrDefaultAsync(o => o.OrderId == orderId);
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        public async Task<Order> CreateAsync(OrderCreateRequest request)
        {
            try
            {
                // 验证商品是否存在且状态为"在售"
                var product = await _context.Products
                    .Include(p => p.User)
                    .FirstOrDefaultAsync(p => p.ProductId == request.ProductId);
                
                if (product == null)
                {
                    throw new Exception($"商品不存在 (ID: {request.ProductId})");
                }
                
                if (product.Status != "在售")
                {
                    throw new Exception($"商品当前不可购买，状态为: {product.Status}");
                }

                // 验证用户是否存在
                var user = await _context.Users.FindAsync(request.UserId);
                if (user == null)
                {
                    throw new Exception($"用户不存在 (ID: {request.UserId})");
                }

                // 检查是否是自己的商品
                if (product.UserId == request.UserId)
                {
                    throw new Exception("不能购买自己发布的商品");
                }

                // 创建新订单，设置默认状态为"待付款"
                var order = new Order
                {
                    OrderId = Guid.NewGuid(),
                    UserId = request.UserId,
                    ProductId = request.ProductId,
                    CreateTime = DateTime.Now,
                    Status = "待付款"  // 明确设置默认状态
                };

                await _context.Orders.AddAsync(order);
                await _context.SaveChangesAsync();

                return await GetByIdAsync(order.OrderId);
            }
            catch (DbUpdateException ex)
            {
                throw new Exception($"数据库更新失败: {ex.InnerException?.Message ?? ex.Message}");
            }
            catch (Exception ex)
            {
                throw new Exception($"创建订单失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        public async Task<Order> UpdateStatusAsync(Guid orderId, string status)
        {
            // 验证状态是否有效
            if (!IsValidOrderStatus(status))
            {
                throw new Exception($"无效的订单状态: {status}");
            }

            var order = await _context.Orders.FindAsync(orderId);
            if (order == null)
            {
                throw new Exception("订单不存在");
            }

            order.Status = status;
            await _context.SaveChangesAsync();

            return await GetByIdAsync(orderId);
        }

        /// <summary>
        /// 验证订单状态是否有效
        /// </summary>
        private bool IsValidOrderStatus(string status)
        {
            return status switch
            {
                Order.STATUS_PENDING_PAYMENT => true,
                Order.STATUS_COMPLETED => true,
                Order.STATUS_CANCELLED => true,
                Order.STATUS_PENDING_SHIPMENT => true,
                Order.STATUS_IN_TRANSIT => true,
                Order.STATUS_PENDING_RECEIPT => true,
                Order.STATUS_RETURNING => true,
                Order.STATUS_EXCHANGING => true,
                Order.STATUS_REFUNDING => true,
                Order.STATUS_PARTIAL_REFUND => true,
                Order.STATUS_REJECTED => true,
                Order.STATUS_AFTER_SALES => true,
                Order.STATUS_FROZEN => true,
                _ => false
            };
        }

        /// <summary>
        /// 获取用户的订单列表（买家）
        /// </summary>
        public async Task<List<Order>> GetByUserIdAsync(Guid userId)
        {
            return await _context.Orders
                .Include(o => o.Product)
                .Where(o => o.UserId == userId)
                .OrderByDescending(o => o.CreateTime)
                .ToListAsync();
        }

        /// <summary>
        /// 获取商品的订单列表
        /// </summary>
        public async Task<List<Order>> GetByProductIdAsync(Guid productId)
        {
            return await _context.Orders
                .Include(o => o.User)
                .Where(o => o.ProductId == productId)
                .OrderByDescending(o => o.CreateTime)
                .ToListAsync();
        }

        public async Task<ActionResult<IEnumerable<Order>>> GetOrders()
        {
            var orders = await _context.Orders
                .Include(o => o.Product)
                .Include(o => o.User)
                .ToListAsync();
            return new JsonResult(orders, _jsonOptions);
        }

        public async Task<ActionResult<Order>> GetOrder(Guid id)
        {
            var order = await _context.Orders
                .Include(o => o.Product)
                .Include(o => o.User)
                .FirstOrDefaultAsync(o => o.OrderId == id);

            if (order == null)
            {
                return new NotFoundResult();
            }

            return new JsonResult(order, _jsonOptions);
        }

        public async Task<ActionResult<IEnumerable<Order>>> GetUserOrders(Guid userId)
        {
            var orders = await _context.Orders
                .Include(o => o.Product)
                .Include(o => o.User)
                .Where(o => o.UserId == userId)
                .ToListAsync();
            return new JsonResult(orders, _jsonOptions);
        }
    }
} 